package com.example.bailin.giftsay.guide;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Toast;

import com.example.bailin.giftsay.R;
import com.example.bailin.giftsay.baseclass.BaseFragment;
import com.example.bailin.giftsay.entity.CarouselEntity;
import com.example.bailin.giftsay.entity.GuanZhuEntity;
import com.example.bailin.giftsay.entity.HomeCellEntity;
import com.example.bailin.giftsay.entity.SpecialEntity;
import com.example.bailin.giftsay.guide.activity.NickNameActivity;
import com.example.bailin.giftsay.guide.activity.WebViewActivity;
import com.example.bailin.giftsay.guide.adapter.CarouselAdapter;
import com.example.bailin.giftsay.guide.adapter.DotAdapter;
import com.example.bailin.giftsay.guide.adapter.SelectionAdapter;
import com.example.bailin.giftsay.guide.adapter.SpecialAdapter;
import com.example.bailin.giftsay.sort.LmClickListener;
import com.example.bailin.giftsay.sort.activity.LmSkipActivity;
import com.example.bailin.giftsay.tool.DBTool;
import com.example.bailin.giftsay.tool.MyApp;
import com.example.bailin.giftsay.tool.MyListView;
import com.example.bailin.giftsay.tool.NetTool;
import com.example.bailin.giftsay.tool.UrlProvide;

import java.util.ArrayList;

/**
 * Created by bailin on 16/8/15.
 * <p>
 * 单独处理精选页的Fragment
 */
public class SelectionFragment extends BaseFragment {

    private View view;
    private ViewPager vp;
    private RecyclerView rv;
    private RecyclerView rvDot;
    private DotAdapter dotAdapter;
    private SelectionAdapter selectionAdapter;
    private Handler mHandler;
    private MyListView lv;
    private String userName;
    private int type = 2;

    @Override
    protected int setLayout() {
        return R.layout.fragment_mylistview;
    }

    @Override
    protected void initView() {
        lv = bindView(R.id.mylv_id);
        view = LayoutInflater.from(MyApp.getContext()).inflate(R.layout.item_listview_selection_title, null);
        vp = (ViewPager) view.findViewById(R.id.vp_selection_titile);
        rv = (RecyclerView) view.findViewById(R.id.rv_selection_title);
        rvDot = (RecyclerView) view.findViewById(R.id.rv_selection_dot);

        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                Message message = mHandler.obtainMessage();
                message.what = 1;
                mHandler.sendMessageDelayed(message, 5000);
                vp.setCurrentItem(vp.getCurrentItem() + 1);
                return false;
            }
        });
        Message message = mHandler.obtainMessage();
        message.what = 1;
        mHandler.sendMessageDelayed(message, 5000);
    }

    @Override
    public void onStop() {
        super.onStop();
        mHandler.removeMessages(1);
    }

    @Override
    protected void initData() {
        SharedPreferences shared = MyApp.getContext().getSharedPreferences(UrlProvide.NAME, MyApp.getContext().MODE_PRIVATE);
        userName = shared.getString("username", "未登录");



        // 轮播图小圆点
        dotAdapter = new DotAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(MyApp.getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvDot.setLayoutManager(manager);
        rvDot.setAdapter(dotAdapter);

        // 精选轮播图的网络处理
        tool().getData(UrlProvide.CAROUSEL, CarouselEntity.class, new NetTool.NetInterface<CarouselEntity>() {
            @Override
            public void onSuccess(CarouselEntity carouselEntity) {
                CarouselAdapter carouselAdapter = new CarouselAdapter();
                carouselAdapter.setCarouselEntity(carouselEntity);
                vp.setAdapter(carouselAdapter);
                vp.setCurrentItem(1000, false);
                // 给轮播图的小点传轮播图片的数量
                dotAdapter.setIndex(carouselEntity.getData().getBanners().size());
            }

            @Override
            public void onError(String errorMsg) {
            }
        });

        // 精选小方框图片网络处理
        tool().getData(UrlProvide.SPECIAL, SpecialEntity.class, new NetTool.NetInterface<SpecialEntity>() {
            @Override
            public void onSuccess(SpecialEntity specialEntity) {
                SpecialAdapter specialAdapter = new SpecialAdapter();
                specialAdapter.setSpecialEntity(specialEntity);
                GridLayoutManager manager = new GridLayoutManager(MyApp.getContext(), 1);
                manager.setOrientation(GridLayoutManager.HORIZONTAL);
                rv.setLayoutManager(manager);
                rv.setAdapter(specialAdapter);
            }

            @Override
            public void onError(String errorMsg) {
            }
        });

        //精选ListView的网络处理
        tool().getData(UrlProvide.HOME_CELL, HomeCellEntity.class, new NetTool.NetInterface<HomeCellEntity>() {
            @Override
            public void onSuccess(final HomeCellEntity homeCellEntity) {
                selectionAdapter = new SelectionAdapter();
                selectionAdapter.setHomeCellEntity(homeCellEntity);
                lv.setAdapter(selectionAdapter);
                lv.addHeaderView(view);

                selectionAdapter.setStoreLvListener(new StoreLvListener() {
                    @Override
                    public void onClick(HomeCellEntity homeCellEntity, int position) {
                        if (!userName.equals("未登录")) {
                            if (type == 2) {
                                GuanZhuEntity entity = new GuanZhuEntity();
                                entity.setCount("" + homeCellEntity.getData().getItems().get(position).getLikes_count());
                                entity.setData(System.currentTimeMillis());
                                entity.setImgUrl(homeCellEntity.getData().getItems().get(position).getCover_image_url());
                                entity.setPrice(homeCellEntity.getData().getItems().get(position).getAuthor().getNickname());
                                entity.setTitle(homeCellEntity.getData().getItems().get(position).getColumn().getTitle());
                                entity.setUserName(userName);
                                entity.setType("2");
                                DBTool.getInstance().insertEntity(entity);
                                type = 1;

                            } else {
                                DBTool.getInstance().deleteGuanZhu("userName = ?", "title = ?", userName, homeCellEntity.getData().getItems().get(position).getColumn().getTitle());
                                type = 2;
                            }
                        }
                    }
                });

                // 跳转到栏目页
                selectionAdapter.setLmClickListener(new LmClickListener() {
                    @Override
                    public void onClick(int id, String title) {
                        Intent intent = new Intent(MyApp.getContext(), LmSkipActivity.class);
                        intent.putExtra("id", id);
                        intent.putExtra("title", title);
                        startActivity(intent);
                    }
                });
                // 跳转到WebView
                selectionAdapter.setPopupClick(new PopupClick() {
                    @Override
                    public void itemOnClick(int position) {
                        Intent intent = new Intent(MyApp.getContext(), WebViewActivity.class);
                        intent.putExtra("url", homeCellEntity.getData().getItems().get(position).getUrl());
                        startActivity(intent);
                    }
                });

                // 跳转到作者页
                selectionAdapter.setNickNListener(new NickNListener() {
                    @Override
                    public void onClick(int id, String imgUrl, String name) {
                        Intent intent = new Intent(MyApp.getContext(), NickNameActivity.class);
                        intent.putExtra("imgUrl", imgUrl);
                        intent.putExtra("name", name);
                        intent.putExtra("id", id);
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onError(String errorMsg) {
            }
        });

        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                dotAdapter.setCount(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        lv.setonRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new AsyncTask<Void, Void, Void>(){

                    @Override
                    protected Void doInBackground(Void... params) {

                        try {
                            Thread.sleep(1800);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        selectionAdapter.notifyDataSetChanged();
                        lv.onRefreshComplete();
                    }
                }.execute(null, null, null);
            }
        });
    }
}